import { addNews, removeNews, updateNews, queryNews } from './service';

const Model = {
  namespace: 'dynamic',
  state: {
    list: [],
    content: [],
  },
  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryNews, payload);
      yield put({
        type: 'save',
        payload: response,
      });
    },

    *add({ payload, callback }, { call, put }) {
      const response = yield call(addNews, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeNews, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateNews, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      if (callback) callback();
    },

    *appendFetch({ payload }, { call, put }) {
      const response = yield call(queryNews, payload);
      yield put({
        type: 'appendList',
        payload: Array.isArray(response) ? response : [],
      });
    },

    *submit({ payload }, { call, put }) {
      let callback;

      if (payload.id) {
        callback = Object.keys(payload).length === 1 ? removeNews : updateNews;
      } else {
        callback = addNews;
      }

      const response = yield call(callback, payload); // post

      yield put({
        type: 'save',
        payload: response,
      });
    },
  },

  reducers: {
    save(state, action) {
      return { ...state, content: action.payload.content };
    },

    appendList(state = { list: [] }, action) {
      return { ...state, list: state.list.concat(action.payload) };
    },
  },
};
export default Model;
